import { mapState, mapGetters } from 'vuex'

var vm = {
    data() {
        return {
            // 产品列表
            productList: null,
            // 额度列表
            amountList: null,
            // 期限列表
            daysList: null,
            // 最新活动
            newActivity: null,
            // 显示优惠信息
            privilegeShow: false,
            // 活动框是否显示
            activityShow: false,
            // 优惠券显示索引
            privilegeIndex: 0,
            // 可用红包列表
            usableRedList: [],
            // 可用免息券列表
            usableFreeList: [],
            // 选择的额度索引
            amountIndex: 0,
            // 选择的期限索引
            daysIndex: 0,
            // 选中的红包
            selectedRedLi: null,
            // 选中的免息券
            selectedFreeLi: null
        }
    },
    computed: {
        ...mapState(['user']),
        ...mapGetters(['userLogined', 'userCreditNums', 'userStatus', 'userBorrowStatus']),
        // 最大可选额度索引
        amountlimitIndex() {
            if (!this.userLogined) {
                return 2
            }
            var { useLimit } = this.user
            var { amountList } = this
            for (var i = 0; i < amountList.length; i++) {
                var amount = amountList[i]
                if (useLimit < amount) {
                    return i
                }
            }
            return amountList.length
        },
        // 额度
        amount() {
            if (this.amountList == null) return 0
            return this.amountList[this.amountIndex]
        },
        // 期限
        days() {
            if (this.daysList == null) return 0
            return this.daysList[this.daysIndex]
        },
        // 选择的产品
        productSelected() {
            var { productList, daysIndex, amountIndex, amount, days } = this
            if (daysIndex == 0 || amountIndex == 0) {
                return {}
            }
            for (var i = 0; i < productList.length; i++) {
                var product = productList[i]
                if (product.amount == amount && product.days == days) {
                    return product
                }
            }
        },
        managementFee() {
            var { managementFee } = this.productSelected
            if (this.selectedRedLi && this.selectedRedLi.amount) {
                return Math.max(managementFee - this.selectedRedLi.amount, 0)
            } else {
                return managementFee
            }
        },
        // // 审核费
        // vettingFee() {
        //     var vettingFee = this.productSelected.vettingFee
        //     if (vettingFee == null) {
        //         // 未选择任何借款
        //         return '--'
        //     } else {
        //         if (this.selectedRedLi) {
        //             // 选择红包
        //             var redAmount = this.selectedRedLi.amount
        //             var disVettingFee = vettingFee - redAmount
        //             return disVettingFee > 0 ? disVettingFee : 0
        //         } else {
        //             // 未选择红包
        //             return vettingFee
        //         }
        //     }
        // },
        // // 服务费
        // serviceFee() {
        //     var { vettingFee, serviceFee } = this.productSelected
        //     if (vettingFee == null || serviceFee == null) {
        //         // 未选择任何借款
        //         return '--'
        //     } else {
        //         if (this.selectedRedLi) {
        //             // 选择红包
        //             var redAmount = this.selectedRedLi.amount
        //             if (vettingFee >= redAmount) {
        //                 // 如果审核费大于红包金额
        //                 return serviceFee
        //             } else {
        //                 // 审核费小于红包金额
        //                 var disServiceFee = vettingFee + serviceFee - redAmount
        //                 return disServiceFee > 0 ? disServiceFee : 0
        //             }
        //         } else {
        //             // 未选择红包
        //             return serviceFee
        //         }
        //     }
        // },
        // // 管理费
        // managementFee() {
        //     var { vettingFee, serviceFee, managementFee } = this.productSelected
        //     if (vettingFee == null || serviceFee == null || managementFee == null) {
        //         // 未选择任何借款
        //         return '--'
        //     } else {
        //         if (this.selectedRedLi) {
        //             // 选择红包
        //             var redAmount = this.selectedRedLi.amount
        //             if (vettingFee + serviceFee >= redAmount) {
        //                 // 如果审核费和服务费大于红包金额
        //                 return managementFee
        //             } else {
        //                 // 审核费和服务费小于红包金额
        //                 var disServiceFee = vettingFee + serviceFee + managementFee - redAmount
        //                 return disServiceFee > 0 ? disServiceFee : 0
        //             }
        //         } else {
        //             // 未选择红包
        //             return managementFee
        //         }
        //     }
        // },
        // 利息
        interest() {
            var { interest } = this.productSelected
            if (interest == null) {
                // 未选择产品
                return '--'
            } else {
                // 选择产品
                if (this.selectedFreeLi) {
                    // 选择免息券
                    var { upApr } = this.selectedFreeLi
                    return ((100 - upApr) * interest) / 100
                } else {
                    // 未选择免息券
                    return interest
                }
            }
        }
    },
    // 在进入路由之前，要获得产品列表信息，若网络异常，则跳转网络异常页面
    beforeRouteEnter(to, from, next) {
        // 如果借款中状态则跳转到借款信息页面
        if ($store.getters.userLogined) {
            $loading.show()
            $store.dispatch('userInfoAjax').then(res => {
                var { code, data, msg } = res.data
                if (code == 'S') {
                    $loading.hide()
                    var { borrowStatus } = data
                    if (borrowStatus == 'Y') {
                        $router.replace('/loan/info')
                    } else {
                        next()
                    }
                } else {
                    $toast.show(msg)
                }
            }).catch(err => {
                $loading.hide()
                $router.replace('/system/neterror')
            })
        } else {
            next()
        }
    },
    mounted() {
        // 产品列表数据 - 重要但不需要登录
        $loading.show()
        $ajax.product.list().then(res => {
            $loading.hide()
            var { code, data } = res.data
            if (code == 'S') {
                this.productList = data.productList
                this.initLoanList()
            }
        }).catch(err => {
            $loading.hide()
            $router.replace('/system/neterror')
        })
        // 最新活动提交的数据
        var activityPostData = {
            activityId: window.localStorage.getItem('activityId') || 0,
            viewDate: window.localStorage.getItem('viewDate') || ''
        }
        // 登录状态中
        if (this.userLogined) {
            // 可以借款的状态
            if (this.userBorrowStatus == 'N') {
                // 红包
                $ajax.user.usableRedList({ userId: this.user.userId, pageNo: 1, pageSize: 9999 }).then(res => {
                    var { code, data } = res.data
                    if (code == 'S') {
                        this.usableRedList = data.list
                    }
                })
                // 免息券
                $ajax.user.usableFreeList({ userId: this.user.userId, pageNo: 1, pageSize: 9999 }).then(res => {
                    var { code, data } = res.data
                    if (code == 'S') {
                        this.usableFreeList = data.list
                    }
                })
                // 最新活动
                // 最新活动需要提交userId
                activityPostData.userId = this.user.userId
                this.activityAjax(activityPostData)
            }
            if (this.userBorrowStatus == 'C' || this.user.status == '4') {
                // 如果为借款审核状态中或这用户审核状态，轮询最新信息
                $store.dispatch('userRefreshAjax')
            }
        } else {
            // 最新活动
            this.activityAjax(activityPostData)
        }
    },
    beforeRouteLeave: (to, from, next) => {
        // 页面跳转之后，关闭轮询
        $store.dispatch('userRefreshAjax', { close: true })
        next()
    },
    methods: {
        // 借款
        loan() {
            var status = this.user.status
            if (this.amount == 0 || this.days == 0) {
                $toast.show('请先选择借款金额和期限')
            } else if (!this.userLogined) {
                $toast.show('请先登录')
                $router.push({
                    name: 'user_login'
                })
            } else if (status == 0 || status == 1 || status == 3) {
                $toast.show({
                    0: '请认证身份证信息',
                    1: '请去认证个人信息',
                    3: '请去认证中心提交'
                }[status])
                $router.push('/loan/cacenter')
            } else {
                var { productId } = this.productSelected
                var borrowApplyData = {
                    userId: this.user.userId,
                    productId
                }
                if (this.selectedRedLi) {
                    borrowApplyData.redId = this.selectedRedLi.redId
                }
                if (this.selectedFreeLi) {
                    borrowApplyData.couponId = this.selectedFreeLi.couponId
                }
                $store.commit('borrowClear')
                $loading.show()
                $ajax.order.borrowApply(borrowApplyData)
                    .then(res => {
                        var { code, msg, data } = res.data
                        if (code == 'S') {
                            $loading.hide()
                            $wxsdk.postLbs({
                                scene: 6,
                                mobile: this.user.mobile,
                                userId: this.user.userId
                            })
                            $store.commit('borrowUpdate', data)
                            $router.replace('/loan/detail')
                        } else {
                            $toast.show(msg)
                        }
                    })
                    .catch(err => {
                        $toast.show('网络异常，请稍后重试')
                    })
            }
        },
        openPop() {
            this.privilegeShow = true
        },
        // 初始化借款列表数据
        initLoanList() {
            var amountList = [0]
            var amountHelp = {}
            var daysList = [0]
            var daysHelp = {}
            for (var i = 0; i < this.productList.length; i++) {
                var product = this.productList[i]
                var { amount, days } = product
                if (!amountHelp[amount]) {
                    amountHelp[amount] = true
                    amountList.push(amount)
                }
                if (!daysHelp[days]) {
                    daysHelp[days] = true
                    daysList.push(days)
                }
            }
            amountList.sort((a, b) => {
                return a - b
            })
            daysList.sort((a, b) => {
                return a - b
            })
            this.amountList = amountList
            this.daysList = daysList
        },
        // 选择红包
        selectRed(redLi) {
            if (this.selectedRedLi && this.selectedRedLi.redId == redLi.redId) {
                // 取消选择红包
                this.selectedRedLi = null
            } else {
                // 选择红包
                this.selectedRedLi = redLi
            }
        },
        // 选择加息券
        selectFree(freeLi) {
            if (this.selectedFreeLi && this.selectedFreeLi.couponId == freeLi.couponId) {
                this.selectedFreeLi = null
            } else {
                this.selectedFreeLi = freeLi
            }
        },
        // 获取最新活动
        activityAjax(postData) {
            // 最新活动
            $ajax.activity.new(postData).then(res => {
                var { code, data } = res.data
                if (code == 'S') {
                    this.activityShow = true
                    this.newActivity = data
                    window.localStorage.setItem('activityId', data.activityId)
                    window.localStorage.setItem('viewDate', data.viewDate || '')
                }
            })
        },
        // 跳转到活动详情页面
        goActivityDo(jumpUrl) {
            if (jumpUrl && jumpUrl.length > 0) window.location.href = jumpUrl
        }
    },
    watch: {
        userBorrowStatus(newVal, oldVal) {
            if (newVal == 'Y') {
                if (oldVal == 'C') {
                    $router.replace('/loan/info')
                }
            }
        }
    }
}

export default vm